package com.coda.service.impl;

import com.coda.common.PageResult;
import com.coda.context.BaseContext;
import com.coda.dto.PageDto;
import com.coda.entity.InStore;
import com.coda.entity.Product;
import com.coda.entity.Purchase;
import com.coda.entity.Store;
import com.coda.mapper.InStoreMapper;
import com.coda.mapper.ProductMapper;
import com.coda.mapper.PurchaseMapper;
import com.coda.service.InStoreService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

@Service
public class InStoreServiceImpl implements InStoreService {

    @Autowired
    private InStoreMapper inStoreMapper;
    @Autowired
    private PurchaseMapper purchaseMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 生成表单入库
     * @param purchase
     */
    @Override
    @Transactional
    public void addInstore(Purchase purchase) {

        purchaseMapper.updateInStoreById(purchase.getBuyId());
        InStore inStore = new InStore();
        inStore.setProductId(purchase.getProductId());
        inStore.setStoreId(purchase.getStoreId());
        inStore.setInNum(purchase.getFactBuyNum());
        inStore.setCreateBy(BaseContext.getCurrentId());
        inStore.setCreateTime(LocalDateTime.now());
        inStore.setIsIn(0);
        inStoreMapper.insert(inStore);
    }

    /**
     * 分页查询入库列表
     * @param pageDto
     * @param
     * @return
     */
    @Override
    public PageResult getInstorePage(PageDto pageDto, InStore inStore) {
        //设置分页参数
        PageHelper.startPage(pageDto.getPageNum(),pageDto.getPageSize());
        //分页查询
        Page<InStore> page = inStoreMapper.getPage(inStore);
        PageResult pageResult = new PageResult(page.getTotal(),page.getResult());
        return pageResult;
    }

    /**
     * 确定入库
     * @param inStore
     */
    @Transactional
    @Override
    public void isStoreOk(InStore inStore) {

        //更新入库状态
        inStoreMapper.updateIsStoreById(inStore);

        Product product = new Product();
        product.setProductId(inStore.getProductId());
        product.setProductInvent(inStore.getInNum());
        //更新商品库存
        productMapper.update(product);
    }
}
